package com.lc.zpyh.ui.activity.supermarket;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lc.zpyh.R;
import com.lc.zpyh.aop.SingleClick;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.AgreeAndContinueApi;
import com.lc.zpyh.http.request.OrderInformationApi;
import com.lc.zpyh.http.request.PayImmediatelyApi;
import com.lc.zpyh.http.response.AgreeAndContinueBean;
import com.lc.zpyh.http.response.OrderInformationBean;
import com.lc.zpyh.http.response.PayImmediatelyBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.PayResult;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.util.eventbus.EventBusUtils;
import com.lc.zpyh.view.CountDownView;
import com.lc.zpyh.widget.UIHelper;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends AppActivity {
    @BindView(R.id.tv_countdown)
    TextView tvCountdown;
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R.id.iv_weixin_iv)
    ImageView ivWeixinIv;
    @BindView(R.id.iv_alipay_iv)
    ImageView ivAlipayIv;
    CountDownTimer timer;
    @BindView(R.id.titlebar)
    TitleBar titlebar;
    @BindView(R.id.rv_zyf)
    RecyclerView rvZyf;
    @BindView(R.id.tv_zyf)
    TextView tvZyf;
    @BindView(R.id.ll_zyf)
    LinearLayout llZyf;
    private String cartIds;
    private String Orderid = "";
    private String orderNum = "";
    private int paymentPlatform = 1;
    private String methodPayment = "微信支付";
    //    优惠券id
    private String yhj = "0";
    //    支付总价
    private String zzfj = "0";
    private String addressid;
    private String merchantids;
    //    备注
    private String infos = "";
    private String yytime;
    private String acct;
    private CountDownView mTimerMin;
    private String orderId = "";
    private String actualAmountPaid;
    private static final String TAG = "PayActivity";
    private String erro = "";
    String appId = "wx87cec1b00a3702d4";
    private BaseQuickAdapter<String, BaseViewHolder> zhyadapter;
    List<String> dataBeanList = new ArrayList<>();
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.show("支付成功");

                    } else {
                        ToastUtils.show("支付失败");

                    }
                    OrderInformation();
                    break;
            }
        }
    };
    private static final int SDK_PAY_FLAG = 100;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
//


        titlebar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {

                EventBusUtils.sendEvent(new Event(EvenConstant.PAYSTAUTS));
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });


        if (getIntent().getStringExtra("zzfj") != null) {
            zzfj = BigDecimalUtils.mul(getIntent().getStringExtra("zzfj") + "", "100", 0);
        }


        orderNum = getIntent().getStringExtra("orderNumber");

        Log.e(TAG, "onCreate: " + zzfj);
        if (getIntent().getStringExtra("appointmentTime") != null) {
            yytime = getIntent().getStringExtra("appointmentTime");
            if (!yytime.isEmpty()) {
                yytime = yytime + ":00";
            }
        }
        Log.e("tag", "onCreate: " + yytime);
        orderId = getIntent().getStringExtra("orderId");
        Log.e("taga", "onCreate: " + orderId);
        actualAmountPaid = getIntent().getStringExtra("actualAmountPaid");
        if (zzfj != null || !zzfj.isEmpty()) {
            tvPayMoney.setText(BigDecimalUtils.div(zzfj + "", "100", 2) + "");
        }
        if (orderId != null) {
//          再次支付

            AgreeAndContinue();
        }


    }

    private void AgreeAndContinue() {

        EasyHttp.post(this)
                .api(new AgreeAndContinueApi().setOrderid(orderId)).request(new HttpCallback<AgreeAndContinueBean>(this) {

            @Override
            public void onSucceed(AgreeAndContinueBean data) {
//
                if (data.getError() == 0) {
                    orderNum = data.getOrderNum();
                    tvPayMoney.setText(BigDecimalUtils.div(data.getOrderSumPrice() + "", "100", 2) + "");
//                    dataBeanList.addAll(data.getCanteenName());
//
//                    zhyadapter = new BaseQuickAdapter<String, BaseViewHolder>
//                            (R.layout.item_zyf, dataBeanList) {
//
//                        @Override
//                        protected void convert(BaseViewHolder baseViewHolder, String dataBean) {
//                            baseViewHolder.setText(R.id.tv_canteenName, dataBean);
//                            baseViewHolder.setText(R.id.tv_yf, "配送费：" + BigDecimalUtils.div(data.getYf() + "", "100", 0) + "元");
//
//                        }
//                    };
//
//
//                    rvZyf.setAdapter(zhyadapter);
//                    tvZyf.setText("合计：" + BigDecimalUtils.div(data.getOrderSumPrice() + "", "100", 2) + "元，含配送费：" + BigDecimalUtils.div(data.getZyf() + "", "100", 2) + "元");
//                    llZyf.setVisibility(View.VISIBLE);

                } else {
                    toast(data.getMsg());
                }

            }

            @Override
            public void onFail(Exception e) {

                erro = "系统错误";
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBusUtils.sendEvent(new Event(EvenConstant.PAYSTAUTS));
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        OrderInformation();
    }
    @SingleClick
    @OnClick({R.id.rl_weixin, R.id.rl_alipay, R.id.tv_sure})
    public void onClick(View view) {
//        0是支付宝     1 是微信
        switch (view.getId()) {
            case R.id.rl_weixin:
                paymentPlatform = 1;
                methodPayment = "微信支付";
                ivWeixinIv.setImageResource(R.mipmap.icon_shop_pay_select);
                ivAlipayIv.setImageResource(R.mipmap.icon_shop_pay_emty);
                acct = SPUtil.get(this, IntentKey.OPENID, "");
                break;
            case R.id.rl_alipay:

                paymentPlatform = 0;
                methodPayment = "支付宝支付";
                ivAlipayIv.setImageResource(R.mipmap.icon_shop_pay_select);
                ivWeixinIv.setImageResource(R.mipmap.icon_shop_pay_emty);
                break;

            case R.id.tv_sure:
                if (CourseUtils.isNullOrEmpty(erro)) {
                    if (paymentPlatform==1) {
                        IWXAPI api = WXAPIFactory.createWXAPI(PayActivity.this, appId);
//
                        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                        req.userName = "gh_3d5636f0459b"; // 填小程序原始id
                        req.path = "pages/pay_order/pay_order?orderNumber=" + orderNum;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

                        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                        api.sendReq(req);
                    }else {
//                        aliPay(orderNum);
                        payImmediately();
                    }

                }
                break;
        }
    }

    private void payImmediately() {
        EasyHttp.post(this)
                .api(new PayImmediatelyApi().setOrderNum(orderNum).setPaymentPlatform(paymentPlatform+"")).request(new HttpCallback<PayImmediatelyBean>(this) {

            @Override
            public void onSucceed(PayImmediatelyBean data) {
//
                if (data.getCode()==0){
                    aliPay(data.getList().getPayinfo().getPayinfo());

                }else {
                    toast(data.getMsg());
                }


            }


        });
    }
    private void aliPay(String aipay_order) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(aipay_order, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private void OrderInformation() {
        EasyHttp.post(this)
                .api(new OrderInformationApi().setReqsn(orderNum)).request(new HttpCallback<OrderInformationBean>(this) {

            @Override
            public void onSucceed(OrderInformationBean data) {
//
                if (data.getCode() == 0) {
                    if (data.isList()) {
                        UIHelper.startActivity(PayActivity.this, PayStautsActivity.class);
                        finish();
                    } else {
                        EventBusUtils.sendEvent(new Event(EvenConstant.PAYSTAUTS));
                        finish();
                    }
                }
            }

            @Override
            public void onFail(Exception e) {

                erro = "系统错误";
            }
        });
    }


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode() == EvenConstant.PAYSTAUTS) {
//
            finish();
        }
    }
}
